<template>
  <div class="dashboard" :class="weatherClass">
    <!-- 天气动画效果层 -->
    <div class="weather-effect">
      <!-- 雨滴元素 -->
      <template v-if="isRainy">
        <div v-for="n in 50" :key="n" class="rain-drop" :style="getRandomStyle()"></div>
      </template>

      <!-- 雪花元素 -->
      <template v-if="isSnowy">
        <div v-for="n in 50" :key="n" class="snow-flake" :style="getRandomStyle()"></div>
      </template>

      <!-- 云朵元素 -->
      <template v-if="isCloudy">
        <div v-for="n in 5" :key="n" class="cloud" :style="getRandomCloudStyle()"></div>
      </template>

      <!-- 阳光元素 -->
      <template v-if="isSunny">
        <div class="sun"></div>
        <div class="sun-glow"></div>
      </template>
    </div>
    <div class="content-wrapper">
      <!-- 顶部问候语卡片 -->
      <Card class="greeting-card" :bordered="false">
        <div class="greeting-content">
          <div class="greeting-left">
            <Icon :type="getWeatherIcon" size="40" class="weather-icon" />
            <div class="greeting-text">
              <h2>{{ getGreeting }}</h2>
              <p class="weather-brief">{{ city }} · {{ weather.text }} · {{ weather.temp }}°C</p>
            </div>
          </div>
          <div class="weather-details">
            <div class="weather-item">
              <Icon type="ios-thermometer-outline" />
              <span>体感温度 {{ weather.feelsLike }}°C</span>
            </div>
            <div class="weather-item">
              <Icon type="ios-navigate-outline" />
              <span>{{ weather.windDir }} {{ weather.windScale }}级</span>
            </div>
            <div class="weather-item">
              <Icon type="ios-water-outline" />
              <span>湿度 {{ weather.humidity }}%</span>
            </div>
          </div>
        </div>
      </Card>
    </div>

    <!-- 主要内容区域 -->
    <div class="container">
      <div class="left-section">
        <Card :bordered="false" class="info-card">
          <template #title>
            <Icon type="ios-analytics" />
            <span>数据概览</span>
          </template>
          <div class="data-overview">
  <!-- 当前在线用户卡片 -->
  <Card :bordered="false" class="stat-card">
    <Icon type="ios-people" size="35" class="stat-icon" />
    <p>当前在线用户</p>
    <h3>{{ onlineUserCount }}</h3>
  </Card>

  <!-- 总浏览人数卡片 -->
  <Card :bordered="false" class="stat-card">
    <Icon type="ios-eye" size="35" class="stat-icon" />
    <p>总浏览人数</p>
    <h3>735</h3>
  </Card>

  <!-- 图书总数卡片 -->
  <Card :bordered="false" class="stat-card">
    <Icon type="ios-book" size="35" class="stat-icon" />
    <p>图书总数</p>
    <h3>{{ totalBookCount }}</h3>
  </Card>

  
  <Card :bordered="false" class="stat-card">
    <Icon type="ios-book" size="35" class="stat-icon" />
    <p>用户活跃率</p>
    <h3>580</h3>
  </Card>
</div>
        </Card>
      </div>

      <div class="right-section">
        <Card :bordered="false" class="chart-card">
          <template #title>
            <Icon type="ios-pie" />
            <span>统计图表</span>
          </template>
          <div ref="chart" class="chart"></div>
        </Card>
      </div>
    </div>
  </div>
</template>

<script>
import { userInfo } from "@/api/user";
import * as echarts from "echarts";
import {onlineUsers} from "@/api/user" 
import {getAllbook} from "@/api/library"

export default {
  name: "Dashboard",

  data() {
    return {
      onlineUserCount: 0,  // 在线用户数
      totalViews: 130,     // 总浏览人数，假设此数据为静态
      totalBookCount: 0,   // 图书总数
      city: "",
      weather: {
        text: "",
        temp: "",
        feelsLike: "",
        windDir: "",
        windScale: "",
        humidity: "",
        obsTime: "",
      },
      add_id: "woiesklutp8kcmbo",
      app_secret: "dkpOeGhXVFdEak1ha1ovbjNQMk5FZz09",
      key: "d5c6d0ee832049c5b7f3b62843e1c98e",
      user: {
        userRole: null,
        userName: "",
        userEmail: "",
      },
      chart: null,
    };
  },

  computed: {
    // 获取问候语
    getGreeting() {
      const hour = new Date().getHours();
      let greeting = "";
      let userName = (this.user.userRole == "admin" ? "管理员" : "用户") + "，" + this.user.userName || "访客";

      if (hour >= 5 && hour < 12) {
        greeting = `早安，${userName}`;
      } else if (hour >= 12 && hour < 18) {
        greeting = `午安，${userName}`;
      } else {
        greeting = `晚安，${userName}`;
      }

      return greeting;
    },

    // 获取天气图标
    getWeatherIcon() {
      const weatherText = this.weather.text;
      const weatherMap = {
        晴: "ios-sunny",
        多云: "ios-partly-sunny",
        阴: "ios-cloudy",
        雨: "ios-rainy",
        雪: "ios-snow",
        雾: "ios-cloudy",
      };

      for (let key in weatherMap) {
        if (weatherText?.includes(key)) {
          return weatherMap[key];
        }
      }
      return "ios-partly-sunny";
    },
    // 天气类型判断
    isRainy() {
      return this.weather.text?.includes("雨");
    },

    isSnowy() {
      return this.weather.text?.includes("雪");
    },

    isCloudy() {
      return this.weather.text?.includes("云") || this.weather.text?.includes("阴");
    },

    isSunny() {
      return this.weather.text?.includes("晴");
    },

    // 根据天气设置页面主题类
    weatherClass() {
      if (this.isRainy) return "weather-rainy";
      if (this.isSnowy) return "weather-snowy";
      if (this.isCloudy) return "weather-cloudy";
      if (this.isSunny) return "weather-sunny";
      return "";
    },

    // 卡片样式类
    cardClass() {
      return {
        "card-transparent": this.isRainy || this.isSnowy || this.isCloudy || this.isSunny,
      };
    },
  },

  methods: {

    //获取token
    getCookieToken() {
      return document.cookie
        .split("; ")
        .find((row) => row.startsWith("token="))
        ?.split("=")[1];
    },

    // 获取用户信息
    async fetchUserInfo() {
      try {
        const token = document.cookie
          .split("; ")
          .find((row) => row.startsWith("token="))
          ?.split("=")[1];

        if (!token) {
          throw new Error("未找到登录凭证");
        }

        const res = await userInfo(token);
        if (res.code === 0) {
          this.user = res.data;
        } else {
          throw new Error("获取用户信息失败");
        }
      } catch (error) {
        console.error("获取用户信息失败:", error);
        this.$Message.error(error.message);
        this.$router.push("/login");
      }
    },

    // 初始化图表
    initChart() {
      if (this.chart) {
        this.chart.dispose();
      }

      const chartDom = this.$refs.chart;
      this.chart = echarts.init(chartDom);

      const option = {
        title: {
          text: "用户活动数据",
          left: "center",
        },
        tooltip: {
          trigger: "item",
        },
        legend: {
          orient: "vertical",
          left: "left",
        },
        series: [
          {
            name: "活动来源",
            type: "pie",
            radius: "50%",
            data: [
              { value: 1048, name: "图书借阅" },
              { value: 735, name: "网站浏览" },
              { value: 580, name: "用户活跃率" },
            ],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)",
              },
            },
          },
        ],
      };

      this.chart.setOption(option);
    },

    // 获取天气信息
    async getWeather() {
      try {
        // 获取IP定位
        const ipResponse = await fetch(`https://www.mxnzp.com/api/ip/self?app_id=${this.add_id}&app_secret=${this.app_secret}`);
        const ipData = await ipResponse.json();

        if (!ipData.data?.city) {
          throw new Error("无法获取城市信息");
        }

        const cityName = ipData.data.city.replace(/市/g, "");
        this.city = cityName;

        // 获取城市ID
        const locationResponse = await fetch(`https://geoapi.qweather.com/v2/city/lookup?location=${cityName}&key=${this.key}`);
        const locationData = await locationResponse.json();

        if (!locationData.location?.[0]?.id) {
          throw new Error("无法获取城市ID");
        }

        // 获取天气信息
        const weatherResponse = await fetch(`https://devapi.qweather.com/v7/weather/now?location=${locationData.location[0].id}&key=${this.key}`);
        const weatherData = await weatherResponse.json();

        if (weatherData.code === "200") {
          this.weather = {
            text: weatherData.now.text,
            temp: weatherData.now.temp,
            feelsLike: weatherData.now.feelsLike,
            windDir: weatherData.now.windDir,
            windScale: weatherData.now.windScale,
            humidity: weatherData.now.humidity,
            obsTime: weatherData.now.obsTime,
          };
        } else {
          throw new Error("获取天气信息失败");
        }
      } catch (error) {
        console.error("获取天气信息失败:", error);
        this.$Message.error(error.message);
      }
    },

    // 处理窗口大小变化
    handleResize() {
      if (this.chart) {
        this.chart.resize();
      }
    },
    // 生成随机样式
    getRandomStyle() {
      return {
        left: `${Math.random() * 100}%`,
        animationDelay: `${Math.random() * 2}s`,
        animationDuration: `${0.5 + Math.random() * 0.5}s`,
      };
    },

    // 生成随机云朵样式
    getRandomCloudStyle() {
      return {
        left: `${Math.random() * 100}%`,
        top: `${Math.random() * 50}%`,
        opacity: 0.5 + Math.random() * 0.5,
        transform: `scale(${0.8 + Math.random() * 0.4})`,
      };
    },

    async fetchOnlineUsers() {
      try {
        const response = await onlineUsers();
        this.onlineUserCount = response.data; // 假设接口返回的用户数在 data.count 中
      } catch (error) {
        console.error("获取在线用户数失败:", error);
      }
    },

    async fetchTotalBooks() {
      try {
        const token = this.getCookieToken(); // 替换为实际的 token
        const response = await getAllbook(token);
        this.totalBookCount = response.data.length; // 假设图书总数在 data.count 中
      } catch (error) {
        console.error("获取图书总数失败:", error);
      }
    },
  },

  mounted() {
    this.fetchUserInfo();
    this.getWeather();
    this.initChart();

    window.addEventListener("resize", this.handleResize);
  },

  beforeDestroy() {
    window.removeEventListener("resize", this.handleResize);
    if (this.chart) {
      this.chart.dispose();
      this.chart = null;
    }
  },

  created() {
    // 在组件创建时调用接口获取在线用户数
    this.fetchOnlineUsers();
    this.fetchTotalBooks();
  },
};
</script>

<style scoped>
.dashboard {
  padding: 24px;
  background: #f5f7f9;
  min-height: calc(100vh - 60px);
}

.greeting-card {
  margin-bottom: 24px;
}

.greeting-content {
  padding: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.greeting-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.weather-icon {
  color: #2d8cf0;
}

.greeting-text h2 {
  margin: 0;
  font-size: 24px;
  color: #17233d;
}

.weather-brief {
  margin: 4px 0 0;
  color: #808695;
}

.weather-details {
  display: flex;
  gap: 24px;
}

.weather-item {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #515a6e;
}

.container {
  display: flex;
  gap: 24px;
  margin-top: 24px;
}

.data-overview {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.stat-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: calc(50% - 8px); /* Two cards per row */
  padding: 16px;
  background-color: hwb(0 100% 0%); /* Light gray background */
  border-radius: 8px;
  text-align: center;
  box-shadow: 0 4px 8px rgba(114, 106, 106, 0.3);
}

.stat-icon {
  color: #2d8cf0;
  margin-bottom: 8px;
}

.stat-card p {
  margin: 0;
  font-size: 16px;
  color: #515a6e;
}

.stat-card h3 {
  margin: 8px 0 0;
  font-size: 24px;
  font-weight: bold;
  color: #17233d;
}


.left-section {
  flex: 1;
  min-width: 0;
}

.right-section {
  width: 500px;
}

.info-card,
.chart-card {
  height: 100%;
}

.chart {
  height: 400px;
}

/* 卡片标题样式 */
:deep(.ivu-card-head) {
  padding: 16px;
  border-bottom: 1px solid #e8eaec;
}

:deep(.ivu-card-head-title) {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 响应式布局 */
@media (max-width: 1200px) {
  .container {
    flex-direction: column;
  }

  .right-section {
    width: 100%;
  }
}

@media (max-width: 768px) {
  .greeting-content {
    flex-direction: column;
    gap: 16px;
  }

  .weather-details {
    flex-direction: column;
    gap: 8px;
  }
}

/* 加载动画 */
.spin-icon-load {
  animation: spin-around 1s linear infinite;
}

@keyframes spin-around {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 天气效果容器 */
.weather-effect {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
  z-index: 1;
}

/* 内容包装器 */
.content-wrapper {
  position: relative;
  z-index: 2;
}

/* 天气主题背景 */
/* .weather-rainy {
  background: linear-gradient(to bottom, #2c3e50, #3498db);
}

.weather-snowy {
  background: linear-gradient(to bottom, #2c3e50, #95a5a6);
}

.weather-cloudy {
  background: linear-gradient(to bottom, #2c3e50, #7f8c8d);
}

.weather-sunny {
  background: linear-gradient(to bottom, #2980b9, #6dd5fa);
} */

/* 半透明卡片 */
.card-transparent {
  background: rgba(255, 255, 255, 0.9) !important;
  backdrop-filter: blur(100px);
}

/* 雨滴动画 */
.rain-drop {
  position: absolute;
  width: 2px;
  height: 100px;
  background: linear-gradient(transparent, rgba(172, 152, 152, 0.8));
  animation: rain linear infinite;
}

@keyframes rain {
  0% {
    transform: translateY(-100px);
  }
  100% {
    transform: translateY(calc(100vh + 100px));
  }
}

/* 雪花动画 */
.snow-flake {
  position: absolute;
  width: 6px;
  height: 6px;
  background: white;
  border-radius: 50%;
  animation: snow linear infinite;
}

@keyframes snow {
  0% {
    transform: translateY(-10px) rotate(0deg);
  }
  100% {
    transform: translateY(calc(100vh + 10px)) rotate(360deg);
  }
}

/* 云朵样式 */
.cloud {
  position: absolute;
  width: 100px;
  height: 40px;
  background: rgba(12, 235, 255, 0.4);
  border-radius: 20px;
  animation: float 10s linear infinite;
}

.cloud::before,
.cloud::after {
  content: "";
  position: absolute;
  background: inherit;
  border-radius: 50%;
}

.cloud::before {
  width: 50px;
  height: 50px;
  top: -20px;
  left: 15px;
}

.cloud::after {
  width: 30px;
  height: 30px;
  top: -10px;
  left: 45px;
}

@keyframes float {
  0% {
    transform: translateX(-100%);
  }
  100% {
    transform: translateX(100vw);
  }
}

/* 阳光效果 */
.sun {
  position: absolute;
  top: 50px;
  right: 50px;
  width: 80px;
  height: 80px;
  background: #ffd700;
  border-radius: 50%;
  box-shadow: 0 0 50px #ffd700;
  animation: glow 4s ease-in-out infinite;
}

.sun-glow {
  position: absolute;
  top: 40px;
  right: 40px;
  width: 100px;
  height: 100px;
  background: radial-gradient(circle, rgba(255, 215, 0, 0.3), transparent 70%);
  animation: sun-burst 4s ease-in-out infinite;
}

@keyframes glow {
  0%,
  100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.1);
  }
}

@keyframes sun-burst {
  0%,
  100% {
    transform: scale(1);
    opacity: 0.3;
  }
  50% {
    transform: scale(1.2);
    opacity: 0.5;
  }
}

/* 适配暗色主题 */
/* @media (prefers-color-scheme: dark) {
  .card-transparent {
    background: rgba(45, 45, 45, 0.9) !important;
  }
} */

/* 性能优化 */
.rain-drop,
.snow-flake,
.cloud,
.sun,
.sun-glow {
  will-change: transform;
}
</style>
